package configs

import (
	"database/sql"
	log "github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"time"
)

var db *gorm.DB
var sqlDB *sql.DB

func DB() *gorm.DB {
	return db
}

func Open(dbConfig DBConfig, config *gorm.Config, models ...interface{}) (err error) {

	if config == nil {
		config = &gorm.Config{}

	}

	if config.NamingStrategy == nil {
		config.NamingStrategy = schema.NamingStrategy{
			TablePrefix:   "t_",
			SingularTable: true,
		}
	}

	if db, err = gorm.Open(mysql.New(mysql.Config{
		DSN:                       dbConfig.Url,
		DefaultStringSize:         256,
		SkipInitializeWithVersion: false,
	}), config); err != nil {
		log.Errorf("open database failed: %s", err.Error())
	}

	if sqlDB, err = db.DB(); err == nil {
		sqlDB.SetMaxIdleConns(dbConfig.MaxIdleConnect)
		sqlDB.SetMaxOpenConns(dbConfig.MaxOpenConnect)
		sqlDB.SetConnMaxIdleTime(time.Duration(dbConfig.ConnectMaxIdleTimeSecond) * time.Second)
		sqlDB.SetConnMaxLifetime(time.Duration(dbConfig.ConnectMaxLifeTimeSeconds) * time.Second)
	} else {
		log.Error(err)
	}
	if err = db.AutoMigrate(models...); err != nil {
		log.Errorf("auto migrate tables failed: %s", err.Error())
	}
	return

}
